#include "NMPreHeader.h"
#include "NMEnemyBulletMgr.h"
#include "NMGlobalData.h"

static NMEnemyBulletMgr* gEnemyBulletMgr = NULL;

NMEnemyBulletMgr* NMEnemyBulletMgr::shared()
{
	FUNCTION_ENTER();

	if (gEnemyBulletMgr == NULL)
		gEnemyBulletMgr = new NMEnemyBulletMgr;


	FUNCTION_LEAVE();

	return gEnemyBulletMgr;
}

NMEnemyBulletMgr::NMEnemyBulletMgr(void)
{
	FUNCTION_ENTER();

	if (gEnemyBulletMgr != NULL)
		assert(false);

	batch_ = CCSpriteBatchNode::batchNodeWithFile("bullet.png");

	FUNCTION_LEAVE();
}

NMEnemyBulletMgr::~NMEnemyBulletMgr(void)
{
	FUNCTION_ENTER();

	FUNCTION_LEAVE();
}

void NMEnemyBulletMgr::addToLayer(CCLayer* layer)
{
	FUNCTION_ENTER();

	if (batch_->getParent())
		batch_->removeFromParentAndCleanup(false);
	layer->addChild(batch_, 101);

	FUNCTION_LEAVE();
}

void NMEnemyBulletMgr::addNewBullet(CCPoint pos)
{
	FUNCTION_ENTER();

	NMEnemyBullet* bullet = new NMEnemyBullet(batch_);
	bullet->setPosition(pos);
	batch_->addChild(bullet);

	FUNCTION_LEAVE();
}

void NMEnemyBulletMgr::update(ccTime dt)
{
	FUNCTION_ENTER();

	CCArray* children = batch_->getChildren();
	CCObject* obj;
	CCARRAY_FOREACH(children, obj)
	{
		NMEnemyBullet* bullet = (NMEnemyBullet*)obj;

		if (bullet->isDestroied())
			continue;

		bullet->update(dt);

		if (bullet->isCollision())
		{
			NMGlobalData::shared()->reduceLife(bullet->getPower());
			bullet->destroy();
		}
	} // FOR_EACH

	FUNCTION_LEAVE();
}
